from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from goods.models import SKUImage, SKU
from .image_serializers import ImageSerializer, SKUSerializer
from meiduo_admin.my_paginations import MyPageNumberPagination


class ImageViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = ImageSerializer
    pagination_class = MyPageNumberPagination

    def create(self, request, *args, **kwargs):

        sku_id = request.data.get('sku')
        image = request.FILES.get('image')

        if not all([sku_id, image]):
            return Response('missing argument', status=status.HTTP_400_BAD_REQUEST)

        client = Fdfs_client(settings.CONFIG_URL)
        result = client.upload_by_buffer(image.read())

        if result['Status'] != 'Upload successed.':
            return Response('Upload failed', status=status.HTTP_400_BAD_REQUEST)

        img_url = result['Remote file_id']
        SKUImage.objects.create(sku_id=sku_id, image=img_url)
        SKU.objects.filter(id=sku_id, default_image_url='').update(default_image_url=img_url)

        return Response(status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):

        sku_id = request.data.get('sku')
        image = request.FILES.get('image')
        old_image = self.get_object()

        if not all([sku_id, image, old_image]):
            return Response('missing argument', status=status.HTTP_400_BAD_REQUEST)

        client = Fdfs_client(settings.CONFIG_URL)
        result = client.upload_by_buffer(image.read())

        if result['Status'] != 'Upload successed.':
            return Response('Upload failed', status=status.HTTP_400_BAD_REQUEST)

        img_url = result['Remote file_id']
        SKUImage.objects.filter(sku_id=sku_id, id=old_image.id).update(image=img_url)

        return Response(status=status.HTTP_201_CREATED)


class SKUListView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer
